﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing;

namespace SacMauVN.Admin
{
    public partial class AnhSanPham : System.Web.UI.Page
    {

        private static int IDSanPham;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["sID"] != null)
                {
                    IDSanPham = Convert.ToInt32(Request.QueryString["sID"]);
                    ThemMoiBanner.Visible = false;
                    LoadListBanner(IDSanPham);
                }
            }
        }

        protected void LoadListBanner(int sID)
        {
            string sql = "SELECT * FROM dbo.tblT2BAnhSanPham WHERE IDSanPham = @IDSanPham";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, sID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grvData.DataSource = dt;
            grvData.DataBind();

        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            ThemMoiBanner.Visible = true;
            btnThemMoi.Visible = false;
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            ThemMoiAnhBanner();
            LoadListBanner(IDSanPham);
            ThemMoiBanner.Visible = false;
            btnThemMoi.Visible = true;
        }

        protected void ThemMoiAnhBanner()
        {
            string sql = "INSERT INTO dbo.tblT2BAnhSanPham(IDSanPham,Image,CreateDate)VALUES(@IDSanPham,@Image,GETDATE())";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@IDSanPham", SqlDbType.Int, ParameterDirection.Input, IDSanPham));
            arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        private string UploadFile()
        {
            try
            {
                if (ImgUploadBanner.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../userfiles/product");
                    HttpPostedFile myFile = ImgUploadBanner.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = arrFileName[0] + "_" + DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];

                    // Create a bitmap of the content of the fileUpload control in memory
                    Bitmap originalBMP = new Bitmap(ImgUploadBanner.FileContent);

                    // Calculate the new image dimensions
                    float origWidth = originalBMP.Width;
                    float origHeight = originalBMP.Height;
                    float sngRatio;
                    if (origHeight > origWidth)
                    {
                        sngRatio = origHeight / origWidth;
                    }
                    else
                    {
                        sngRatio = origWidth / origHeight;
                    }
                    int newWidth = 650;
                    int newHeight = Convert.ToInt32(newWidth * sngRatio);

                    // Create a new bitmap which will hold the previous resized bitmap
                    Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                    // Create a graphic based on the new bitmap
                    Graphics oGraphics = Graphics.FromImage(newBMP);
                    // Set the properties for the new graphic file
                    oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    // Draw the new graphic based on the resized bitmap
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                    // Save the new graphic file to the server
                    newBMP.Save(string.Format(@"{0}\{1}", sFolderPath, sFileName));

                    // Once finished with the bitmap objects, we deallocate them.
                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    //myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "userfiles/product/" + sFileName;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;
            if ((sCommandName == SacMauVN.MyConst.Action.Delete))
            {
                string sql = "Select Image from tblT2BAnhSanPham where ID = " + sID;
                DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                string FileName = dt.Rows[0]["tblT2BAnhSanPham"].ToString();
                sql = "DELETE FROM dbo.tblT2BAnhSanPham WHERE ID = " + sID;
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                try
                {
                    File.Delete(Server.MapPath("../" + FileName));
                }
                catch (Exception ex)
                {
                    Response.Write(ex.StackTrace);
                }


            }
            grvData.EditIndex = -1;
            LoadListBanner(IDSanPham);
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            LoadListBanner(IDSanPham);
        }

        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            LoadListBanner(IDSanPham);
        }

        protected void grvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            grvData.DeleteRow(e.RowIndex);
            grvData.DataBind();
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            ThemMoiBanner.Visible = false;
            btnThemMoi.Visible = true;
        }
    }
}
